// import { asyncRoutes, constantRoutes } from '@/router'
// import { getInfo, getMenuList } from '@/api/user'
import { constantRoutes } from '@/router'
import { getMenuList } from '@/api/user'
import Layout from '@/layout/index'
// 新增的，注意要添加要给文件 router/_import_development.js 文件
const _import = require('@/router/_import_' + process.env.NODE_ENV) // 获取组件的方法

// const _import = require('./_import_' + process.env.NODE_ENV)

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
/*
  动态生成路由，注册路由，使字符串形式的路由变成真正的路由
*/
function filterAsyncRouter2(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    console.log('3' + route.component)
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.component) // 导入组件
      }
    }
    if (route.hidden) {
      if (route.hidden === '1') {
        route.hidden = false
      } else if (route.hidden === '0') {
        route.hidden = true
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter2(route.children)
    }
    return true
  })
  console.log('=============')
  return accessedRouters
}
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      getMenuList(roles).then(response => {
        const m = filterAsyncRouter2(response.menu)
        commit('SET_ROUTES', m)
        resolve(m)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
